package com.michael.ims.gateway.component;

import com.michael.common.ex.BusinessException;
import com.michael.io.Error;
import com.michael.io.RespStatus;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.MessageSource;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.server.ServerWebExchange;

import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;

/**
 * 目前先不用，后续可以使用
 */
public class CustomerErrorAttributes implements ErrorAttributes {
    private static Logger logger = LoggerFactory.getLogger(CustomerErrorAttributes.class);
    private static final String ERROR_ATTRIBUTE = CustomerErrorAttributes.class.getName()
            + ".ERROR";

    @Autowired
    private MessageSource messageSource;

    @Override
    public Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
        Map<String, Object> errorAttributes = new LinkedHashMap<>();
        Throwable error = getError(request);
        errorAttributes.put("status", 200);
        Error err = new Error();
        if (error instanceof BusinessException) {
            errorAttributes.put("status", RespStatus.FAIL);

            BusinessException be = (BusinessException) error;
            err.setCode(be.getExpCode());
            if (StringUtils.isNotBlank(be.getMsg())) {
                err.setMessage(be.getMsg());
            } else {
                err.setMessage(messageSource.getMessage(be.getExpCode(), be.getArgs(), "没有找到对应的描述", Locale.getDefault()));
            }
            if (be.getDetails() != null) {
                err.setDetails(be.getDetails());
            }
            errorAttributes.put("error", err);
        } else {
            logger.error("未知异常->{}", error);
            errorAttributes.put("status", RespStatus.ERROR);

            err.setMessage("未知异常");
            err.setDetails(error.getMessage());
            errorAttributes.put("error", err);
        }
        return errorAttributes;
    }

    @Override
    public Throwable getError(ServerRequest request) {
        return (Throwable) request.attribute(ERROR_ATTRIBUTE)
                .orElseThrow(() -> new IllegalStateException(
                        "Missing exception attribute in ServerWebExchange"));
    }

    @Override
    public void storeErrorInformation(Throwable error, ServerWebExchange exchange) {
        exchange.getAttributes().putIfAbsent(ERROR_ATTRIBUTE, error);
    }
}
